package com.ruoyi.fun.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.fun.domain.EcOrder;
import com.ruoyi.fun.domain.EcOrderItem;
import com.ruoyi.fun.domain.EcProduct;
import com.ruoyi.fun.domain.EcProductSku;
import com.ruoyi.fun.service.IEcOrderService;
import com.ruoyi.fun.service.IEcOrderItemService;
import com.ruoyi.fun.service.IEcProductService;
import com.ruoyi.fun.service.IEcProductSkuService;
import com.ruoyi.fun.service.IEcUserAddressService;
import com.ruoyi.fun.domain.EcUserAddress;
import com.ruoyi.fun.service.IEcRefundService;
import com.ruoyi.fun.domain.EcRefund;
import com.ruoyi.fun.service.IEcProductCommentService;
import com.ruoyi.fun.domain.EcProductComment;
import com.ruoyi.fun.service.IEcBrandService;
import com.ruoyi.fun.domain.EcBrand;
import com.ruoyi.fun.service.IEcCategoryService;
import com.ruoyi.fun.domain.EcCategory;
import com.ruoyi.fun.service.IEcLogisticsService;
import com.ruoyi.fun.domain.EcLogistics;
import com.ruoyi.fun.service.IEcStockService;
import java.math.BigDecimal;
import java.util.Date;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.RequestParam;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ServletUtils;
import java.io.IOException;
import java.util.Random;
import java.text.SimpleDateFormat;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.system.service.TencentCosService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * APP订单Controller
 * 
 * @author ruoyi
 * @date 2025-01-27
 */
@Anonymous
@RestController
@RequestMapping("/app/order")
public class AppOrderController extends BaseController
{
    @Autowired
    private IEcOrderService ecOrderService;
    
    @Autowired
    private IEcOrderItemService ecOrderItemService;
    
    @Autowired
    private IEcProductService ecProductService;
    
    @Autowired
    private IEcUserAddressService ecUserAddressService;
    
    @Autowired
    private IEcProductSkuService ecProductSkuService;
    
    @Autowired
    private IEcRefundService ecRefundService;
    
    @Autowired
    private IEcProductCommentService ecProductCommentService;
    
    @Autowired
    private IEcBrandService ecBrandService;
    
    @Autowired
    private IEcCategoryService ecCategoryService;
    
    @Autowired
    private IEcLogisticsService ecLogisticsService;

    @Autowired
    private IEcStockService ecStockService;

    /**
     * 批量检查商品库存
     */
    @PostMapping("/stock/batchCheck")
    public AjaxResult batchCheckStock(@RequestBody List<Map<String, Object>> stockCheckData) {
        try {
            // 调用批量库存检查服务
            Map<Long, Boolean> stockResult = ecStockService.batchCheckStock(stockCheckData);
            
            // 构建响应结果
            Map<String, Object> result = new HashMap<>();
            boolean allAvailable = stockResult.values().stream().allMatch(available -> available);
            result.put("allAvailable", allAvailable);
            result.put("stockDetails", stockResult);
            
            if (!allAvailable) {
                result.put("message", "部分商品库存不足");
            }
            
            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("批量检查库存失败", e);
            return AjaxResult.error("库存检查失败：" + e.getMessage());
        }
    }

    @Autowired
    private TencentCosService tencentCosService;

    private static final Logger logger = LoggerFactory.getLogger(AppOrderController.class);

    /**
     * 查询当前用户的订单列表
     */
    @GetMapping("/list")
    public TableDataInfo list(EcOrder ecOrder, @RequestParam(value = "orgId", required = false) Long orgId)
    {
        // 从请求参数中获取用户ID，支持匿名访问
        Long userId = ecOrder.getUserId();
        if (userId == null) {
            return getDataTable(new java.util.ArrayList<>());
        }
        
        // 设置查询条件为当前用户
        ecOrder.setUserId(userId);
        
        // orgId 通过请求参数传入，如果没有传入则使用默认值
        if (orgId == null) {
            orgId = getOrgId();
        }
        ecOrder.setOrgId(orgId);
        System.out.println("订单列表查询 - 使用的组织ID: " + orgId);
        
        startPage();
        List<EcOrder> list = ecOrderService.selectEcOrderList(ecOrder);
        
        // 确保list不为null
        if (list == null) {
            list = new java.util.ArrayList<>();
        }
        
        return getDataTable(list);
    }

    /**
     * 获取当前用户的订单详细信息
     */
    @GetMapping(value = "/{orderId}")
    public AjaxResult getInfo(@PathVariable("orderId") Long orderId, @RequestParam(value = "userId", required = false) Long userId, @RequestParam(value = "orgId", required = false) Long orgId)
    {
        // 优先从SecurityUtils获取用户ID，如果获取失败则使用传入的userId
        if (userId == null) {
            try {
                userId = SecurityUtils.getUserId();
                System.out.println("从SecurityUtils获取用户ID: " + userId);
            } catch (Exception e) {
                System.out.println("从SecurityUtils获取用户ID失败: " + e.getMessage());
                return error("用户ID不能为空，请先登录");
            }
        } else {
            System.out.println("使用传入的用户ID: " + userId);
        }
        
        if (userId == null) {
            return error("用户ID不能为空");
        }
        
        // orgId 通过请求参数传入，如果没有传入则使用默认值
        if (orgId == null) {
            orgId = getOrgId();
        }
        System.out.println("使用的组织ID: " + orgId);
        
        EcOrder order = ecOrderService.selectEcOrderByOrderIdAndOrgId(orderId, orgId);
        if (order == null) {
            return error("订单数据不存在");
        }
        
        // 验证订单是否属于当前用户
        if (!userId.equals(order.getUserId())) {
            return error("无权限访问此订单");
        }
        
        return success(order);
    }
    
    /**
     * 根据订单ID获取订单商品列表
     */
    @GetMapping("/items/{orderId}")
    public AjaxResult getOrderItems(@PathVariable("orderId") Long orderId, @RequestParam(value = "userId", required = false) Long userId, @RequestParam(value = "orgId", required = false) Long orgId)
    {
        // 优先从SecurityUtils获取用户ID，如果获取失败则使用传入的userId
        if (userId == null) {
            try {
                userId = SecurityUtils.getUserId();
                System.out.println("从SecurityUtils获取用户ID: " + userId);
            } catch (Exception e) {
                System.out.println("从SecurityUtils获取用户ID失败: " + e.getMessage());
                return error("用户ID不能为空，请先登录");
            }
        } else {
            System.out.println("使用传入的用户ID: " + userId);
        }
        
        if (userId == null) {
            return error("用户ID不能为空");
        }
        
        // orgId 通过请求参数传入，如果没有传入则使用默认值
        if (orgId == null) {
            orgId = getOrgId();
        }
        System.out.println("订单商品查询 - 使用的组织ID: " + orgId);
        
        // 先验证订单是否属于当前用户
        EcOrder order = ecOrderService.selectEcOrderByOrderIdAndOrgId(orderId, orgId);
        if (order == null) {
            return error("订单数据不存在");
        }
        
        if (!userId.equals(order.getUserId())) {
            return error("无权限访问此订单");
        }
        
        // 查询订单商品列表
        EcOrderItem queryItem = new EcOrderItem();
        queryItem.setOrderId(orderId);
        queryItem.setOrgId(orgId);
        List<EcOrderItem> itemList = ecOrderItemService.selectEcOrderItemList(queryItem);
        
        return success(itemList);
    }
    
    /**
     * 根据订单号获取订单商品列表
     */
    @GetMapping("/items/by-no/{orderNo}")
    public AjaxResult getOrderItemsByNo(@PathVariable("orderNo") String orderNo)
    {
        // 获取当前登录用户ID
        Long currentUserId = SecurityUtils.getUserId();
        
        // 先根据订单号查询订单
        EcOrder queryOrder = new EcOrder();
        queryOrder.setOrderNo(orderNo);
        queryOrder.setUserId(currentUserId);
        List<EcOrder> orderList = ecOrderService.selectEcOrderList(queryOrder);
        
        if (orderList == null || orderList.isEmpty()) {
            return error("订单数据不存在或无权限访问");
        }
        
        EcOrder order = orderList.get(0);
        
        // 查询订单商品列表
        EcOrderItem queryItem = new EcOrderItem();
        queryItem.setOrderId(order.getOrderId());
        queryItem.setOrderNo(orderNo);
        List<EcOrderItem> itemList = ecOrderItemService.selectEcOrderItemList(queryItem);
        
        return success(itemList);
    }
    
    /**
     * 查询当前用户的订单列表（包含商品详情）
     */
    @GetMapping("/list-with-products")
    public AjaxResult listWithProducts(EcOrder ecOrder, @RequestParam(value = "userId", required = false) Long userId, @RequestParam(value = "orgId", required = false) Long orgId)
    {
        // 优先从SecurityUtils获取用户ID，如果获取失败则使用传入的userId
        if (userId == null) {
            try {
                userId = SecurityUtils.getUserId();
                System.out.println("从SecurityUtils获取用户ID: " + userId);
            } catch (Exception e) {
                System.out.println("从SecurityUtils获取用户ID失败: " + e.getMessage());
                return error("用户ID不能为空，请先登录");
            }
        } else {
            System.out.println("使用传入的用户ID: " + userId);
        }
        
        if (userId == null) {
            return error("用户ID不能为空");
        }
        
        // 如果没有传入orgId，使用默认值
        if (orgId == null) {
            orgId = getOrgId(); // 从BaseController获取默认组织ID
        }
        
        // 设置查询条件为当前用户和组织
        ecOrder.setUserId(userId);
        ecOrder.setOrgId(orgId);
        
        // 如果指定了订单ID，只查询该订单
        if (ecOrder.getOrderId() != null) {
            // 使用带org_id过滤的方法查询订单
            EcOrder order = ecOrderService.selectEcOrderByOrderIdAndOrgId(ecOrder.getOrderId(), orgId);
            if (order == null || !userId.equals(order.getUserId())) {
                return error("订单数据不存在或无权限访问");
            }
            
            List<Map<String, Object>> result = new java.util.ArrayList<>();
            Map<String, Object> orderData = buildOrderWithProducts(order);
            result.add(orderData);
            return success(result);
        }
        
        startPage();
        List<EcOrder> orderList = ecOrderService.selectEcOrderList(ecOrder);
        
        // 为每个订单获取商品列表和商品详情
        List<Map<String, Object>> result = orderList.stream().map(this::buildOrderWithProducts).collect(Collectors.toList());
        
        return success(result);
    }
    
    /**
     * 构建包含商品信息的订单数据
     */
    private Map<String, Object> buildOrderWithProducts(EcOrder order) {
        Map<String, Object> orderData = new HashMap<>();
        orderData.put("order", order);
        
        // 获取订单商品列表（根据订单号查询，不使用org_id过滤）
        EcOrderItem queryItem = new EcOrderItem();
        queryItem.setOrderNo(order.getOrderNo()); // 使用订单号查询
        System.out.println("查询订单商品列表 - 订单号: " + order.getOrderNo());
        List<EcOrderItem> itemList = ecOrderItemService.selectEcOrderItemList(queryItem);
        System.out.println("找到订单商品数量: " + itemList.size());
        
        // 打印订单商品详细信息用于调试
        for (EcOrderItem item : itemList) {
            System.out.println("=== 订单商品项调试信息 ===");
            System.out.println("订单商品ID: " + item.getOrderItemId());
            System.out.println("商品ID: " + item.getProductId());
            System.out.println("SKU ID: " + item.getSkuId());
            System.out.println("商品名称: " + item.getProductName());
            System.out.println("商品图片: " + item.getProductImage());
            System.out.println("商品规格: " + item.getProductSpec());
            System.out.println("商品价格: " + item.getProductPrice());
            System.out.println("购买数量: " + item.getProductQuantity());
            System.out.println("组织ID: " + item.getOrgId());
        }
        
        // 为每个订单商品获取商品详情和SKU信息
        List<Map<String, Object>> itemsWithProducts = itemList.stream().map(item -> {
            Map<String, Object> itemData = new HashMap<>();
            itemData.put("orderItem", item);
            
            // 根据商品ID获取商品详情（直接查询，不使用org_id过滤）
            if (item.getProductId() != null) {
                System.out.println("查询商品信息 - 商品ID: " + item.getProductId());
                EcProduct product = ecProductService.selectEcProductByProductId(item.getProductId());
                
                if (product != null) {
                    System.out.println("商品查询成功 - 商品名称: " + product.getProductName());
                    System.out.println("商品图片: " + product.getMainImage());
                    // 更新订单项的商品信息
                    item.setProductName(product.getProductName());
                    item.setRealProductName(product.getProductName());
                    item.setProductImage(product.getMainImage()); // 设置商品图片
                    // 如果订单项中没有商品价格，使用商品的价格
                    if (item.getProductPrice() == null && product.getPrice() != null) {
                        item.setProductPrice(product.getPrice());
                    }
                    itemData.put("product", product);
                } else {
                    System.out.println("商品查询失败 - 商品ID: " + item.getProductId());
                    // 创建一个默认的商品对象，避免前端显示"未知商品"
                    EcProduct defaultProduct = new EcProduct();
                    defaultProduct.setProductId(item.getProductId());
                    defaultProduct.setProductName("商品信息缺失(ID:" + item.getProductId() + ")");
                    defaultProduct.setMainImage("/static/images/default-product.png");
                    // 更新订单项的商品名称
                    item.setProductName("商品信息缺失(ID:" + item.getProductId() + ")");
                    item.setRealProductName("商品信息缺失(ID:" + item.getProductId() + ")");
                    itemData.put("product", defaultProduct);
                }
            } else {
                System.out.println("订单商品项缺少商品ID");
            }
            
            // 根据SKU ID获取SKU详情（直接查询，不使用org_id过滤）
            if (item.getSkuId() != null) {
                EcProductSku sku = ecProductSkuService.selectEcProductSkuBySkuId(item.getSkuId());
                if (sku != null) {
                    System.out.println("=== SKU信息查询成功 ===");
                    System.out.println("SKU ID: " + sku.getSkuId());
                    System.out.println("SKU名称: " + sku.getSkuName());
                    System.out.println("SKU规格信息: " + sku.getSpecInfo());
                    System.out.println("SKU图片: " + sku.getImage());
                    
                    // 设置SKU信息到订单项中
                    if (sku.getSkuName() != null && !sku.getSkuName().isEmpty()) {
                        item.setSkuName(sku.getSkuName());
                        // 如果有SKU名称，优先使用SKU名称作为商品名称
                        item.setProductName(sku.getSkuName());
                        item.setRealProductName(sku.getSkuName());
                    }
                    
                    // 设置SKU规格信息
                    if (sku.getSpecInfo() != null && !sku.getSpecInfo().isEmpty()) {
                        item.setProductSpec(sku.getSpecInfo());
                        System.out.println("已设置订单项规格信息: " + sku.getSpecInfo());
                    }
                    
                    // 如果SKU有图片，优先使用SKU图片
                    if (sku.getImage() != null && !sku.getImage().isEmpty()) {
                        item.setProductImage(sku.getImage());
                        System.out.println("已设置SKU图片: " + sku.getImage());
                    }
                    
                    // 如果订单项中没有价格，使用SKU价格
                    if (item.getProductPrice() == null && sku.getPrice() != null) {
                        item.setProductPrice(sku.getPrice());
                    }
                } else {
                    System.out.println("=== SKU信息查询失败 ===");
                    System.out.println("SKU ID: " + item.getSkuId());
                }
                itemData.put("sku", sku);
            }
            
            return itemData;
        }).collect(Collectors.toList());
        
        orderData.put("items", itemsWithProducts);
        
        // 计算订单商品总数量
        Long totalQuantity = itemList.stream()
            .mapToLong(item -> item.getProductQuantity() != null ? item.getProductQuantity() : 0L)
            .sum();
        orderData.put("totalQuantity", totalQuantity);
        
        return orderData;
    }

    /**
     * 更新订单状态（通过订单ID）
     */
    @Log(title = "订单状态更新", businessType = BusinessType.UPDATE)
    @PostMapping("/updateStatus/{orderId}/{status}")
    public AjaxResult updateOrderStatus(@PathVariable("orderId") String orderIdOrNo, @PathVariable("status") String status, @RequestParam(value = "userId", required = false) Long userId, @RequestParam(value = "orgId", required = false) Long orgId)
    {
        try {
            // 优先从SecurityUtils获取用户ID，如果获取失败则使用传入的userId
            if (userId == null) {
                try {
                    userId = SecurityUtils.getUserId();
                    System.out.println("从SecurityUtils获取用户ID: " + userId);
                } catch (Exception e) {
                    System.out.println("从SecurityUtils获取用户ID失败: " + e.getMessage());
                    return error("用户ID不能为空，请先登录");
                }
            } else {
                System.out.println("使用传入的用户ID: " + userId);
            }
            
            if (userId == null) {
                return error("用户ID不能为空");
            }
            
            // 如果没有传入orgId，使用默认值
            if (orgId == null) {
                orgId = getOrgId(); // 从BaseController获取默认组织ID
            }
            
            System.out.println("使用的组织ID: " + orgId);
            
            EcOrder order = null;
            
            // 判断传入的是订单ID还是订单号
            if (orderIdOrNo.matches("\\d+")) {
                // 如果是纯数字，按订单ID查询（使用带orgId过滤的方法）
                Long orderId = Long.parseLong(orderIdOrNo);
                order = ecOrderService.selectEcOrderByOrderIdAndOrgId(orderId, orgId);
            } else {
                // 如果不是纯数字，按订单号查询（添加orgId过滤）
                EcOrder queryOrder = new EcOrder();
                queryOrder.setOrderNo(orderIdOrNo);
                queryOrder.setOrgId(orgId);
                List<EcOrder> orderList = ecOrderService.selectEcOrderList(queryOrder);
                if (orderList != null && !orderList.isEmpty()) {
                    order = orderList.get(0);
                }
            }
            
            if (order == null) {
                return AjaxResult.error("订单不存在");
            }
            
            // 验证订单是否属于当前用户（如果是管理员操作则跳过此验证）
            boolean isAdmin = userId != null && userId.equals(1L);
            if (userId != null && !isAdmin && !order.getUserId().equals(userId)) {
                return AjaxResult.error("无权限操作此订单");
            }
            
            // 验证状态转换是否合法（管理员操作跳过部分验证）
            // 注释掉状态转换验证，允许更灵活的状态更新
            String currentStatus = order.getOrderStatus();
            // if (!isValidStatusTransition(currentStatus, status, isAdmin)) {
            //     return AjaxResult.error("订单状态转换不合法");
            // }
            
            // 更新订单状态
            order.setOrderStatus(status);
            
            // 根据状态更新对应的时间字段
            Date currentTime = new Date();
            
            // 如果是支付成功（从待付款1变为待发货2），更新实付金额和支付时间，并扣减库存
            if ("1".equals(currentStatus) && "2".equals(status)) {
                // 支付成功时，实付金额等于订单总金额（如果没有使用优惠券的话）
                if (order.getPaymentAmount() == null) {
                    order.setPaymentAmount(order.getTotalAmount());
                    System.out.println("=== 支付成功，设置实付金额 ===");
                    System.out.println("订单号: " + order.getOrderNo());
                    System.out.println("订单总金额: " + order.getTotalAmount());
                    System.out.println("实付金额: " + order.getTotalAmount());
                }
                // 更新支付时间
                order.setPaymentTime(currentTime);
                System.out.println("=== 更新支付时间 ===");
                System.out.println("订单号: " + order.getOrderNo());
                System.out.println("支付时间: " + currentTime);
                
                // 支付成功后扣减库存
                try {
                    // 获取订单商品列表
                    EcOrderItem queryItem = new EcOrderItem();
                    queryItem.setOrderId(order.getOrderId());
                    List<EcOrderItem> orderItems = ecOrderItemService.selectEcOrderItemList(queryItem);
                    
                    if (orderItems != null && !orderItems.isEmpty()) {
                        // 准备批量扣减库存的数据
                        List<Map<String, Object>> stockDeductList = new java.util.ArrayList<>();
                        
                        for (EcOrderItem item : orderItems) {
                            if (item.getSkuId() != null && item.getProductQuantity() != null) {
                                Map<String, Object> stockItem = new HashMap<>();
                                stockItem.put("skuId", item.getSkuId());
                                stockItem.put("quantity", item.getProductQuantity());
                                stockDeductList.add(stockItem);
                            }
                        }
                        
                        // 批量扣减库存
                        if (!stockDeductList.isEmpty()) {
                            boolean deductResult = ecStockService.batchDeductStock(stockDeductList, order.getOrderNo());
                            if (!deductResult) {
                                logger.error("支付成功但库存扣减失败: orderNo={}", order.getOrderNo());
                                // 库存扣减失败，但支付已成功，记录错误日志，不阻止订单状态更新
                                // 可以考虑发送告警通知管理员处理
                            } else {
                                logger.info("支付成功，库存扣减完成: orderNo={}, 扣减商品数量={}", 
                                           order.getOrderNo(), stockDeductList.size());
                            }
                        }
                        
                        // 更新商品和SKU销量
                        for (EcOrderItem item : orderItems) {
                            if (item.getProductId() != null && item.getProductQuantity() != null) {
                                try {
                                    // 更新商品销量
                                ecProductService.updateProductSaleCount(item.getProductId(), item.getProductQuantity().intValue());
                                logger.info("商品销量更新成功，商品ID：{}，增加数量：{}", item.getProductId(), item.getProductQuantity());
                                
                                // 更新SKU销量（如果有SKU ID）
                                if (item.getSkuId() != null && order.getOrgId() != null) {
                                    System.out.println("\n=== 订单状态更新：开始更新SKU销量 ===");
                                    System.out.println("订单号: " + order.getOrderNo());
                                    System.out.println("SKU ID: " + item.getSkuId());
                                    System.out.println("增加数量: " + item.getProductQuantity());
                                    System.out.println("组织ID: " + order.getOrgId());
                                    
                                    int skuUpdateResult = ecProductSkuService.updateSkuSaleCount(item.getSkuId(), item.getProductQuantity().intValue(), order.getOrgId());
                                    System.out.println("SKU销量更新返回结果: " + skuUpdateResult);
                                    System.out.println("=== 订单状态更新：SKU销量更新完成 ===\n");
                                    
                                    logger.info("SKU销量更新成功，SKU ID：{}，增加数量：{}，组织ID：{}", item.getSkuId(), item.getProductQuantity(), order.getOrgId());
                                } else {
                                    System.out.println("跳过SKU销量更新 - SKU ID: " + item.getSkuId() + ", 组织ID: " + order.getOrgId());
                                }
                                } catch (Exception e) {
                                    logger.error("更新销量失败: orderNo={}, productId={}, skuId={}", 
                                               order.getOrderNo(), item.getProductId(), item.getSkuId(), e);
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error("支付成功后扣减库存异常: orderNo={}", order.getOrderNo(), e);
                    // 库存扣减异常，但支付已成功，记录错误日志，不阻止订单状态更新
                }
            }
            
            // 如果是确认收货（从待收货3变为已完成4），更新收货时间
            if ("3".equals(currentStatus) && "4".equals(status)) {
                order.setReceiveTime(currentTime);
                System.out.println("=== 更新收货时间 ===");
                System.out.println("订单号: " + order.getOrderNo());
                System.out.println("收货时间: " + currentTime);
            }
            
            int result = ecOrderService.updateEcOrder(order);
            
            if (result > 0) {
                return AjaxResult.success("订单状态更新成功");
            } else {
                return AjaxResult.error("订单状态更新失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 验证订单状态转换是否合法
     */
    private boolean isValidStatusTransition(String currentStatus, String newStatus, boolean isAdmin) {
        // 状态说明：1-待付款，2-待发货，3-待收货，4-已完成，5-已取消，6-已退款
        
        // 管理员在退款审核时可以直接将订单状态更新为已退款
        if (isAdmin && "6".equals(newStatus)) {
            // 管理员可以将任何非终态订单设置为已退款（除了已取消和已退款）
            return !"5".equals(currentStatus) && !"6".equals(currentStatus);
        }
        
        switch (currentStatus) {
            case "1": // 待付款
                return "2".equals(newStatus) || "5".equals(newStatus); // 可以支付(变为待发货)或取消
            case "2": // 待发货
                return "3".equals(newStatus) || "5".equals(newStatus); // 可以发货(变为待收货)或取消
            case "3": // 待收货
                return "4".equals(newStatus) || "6".equals(newStatus); // 可以确认收货(变为已完成)或申请退款
            case "4": // 已完成
                return "6".equals(newStatus); // 可以申请退款
            case "5": // 已取消
            case "6": // 已退款
                return false; // 终态，不能再转换
            default:
                return false;
        }
    }
    
    /**
     * 申请退款
     */
    @Log(title = "申请退款", businessType = BusinessType.INSERT)
    @PostMapping("/refund/apply")
    public AjaxResult applyRefund(@RequestBody Map<String, Object> requestData)
    {
        try {
            // 获取当前用户ID和组织ID
            Long userId = SecurityUtils.getUserId();
            
            // 从请求体中获取orgId
             Long orgId = null;
             if (requestData.containsKey("orgId") && requestData.get("orgId") != null) {
                 orgId = Long.valueOf(requestData.get("orgId").toString());
                 logger.info("[退款申请] 使用前端传递的orgId: {}", orgId);
             } else {
                 orgId = getOrgId();
                 logger.info("[退款申请] 使用用户默认orgId: {}", orgId);
             }
             logger.info("[退款申请] 最终使用的orgId: {}", orgId);
            
            // 构建EcRefund对象
            EcRefund refund = new EcRefund();
            if (requestData.containsKey("orderNo")) {
                refund.setOrderNo(requestData.get("orderNo").toString());
            }
            if (requestData.containsKey("refundType")) {
                refund.setRefundType(requestData.get("refundType").toString());
            }
            if (requestData.containsKey("refundReason")) {
                refund.setRefundReason(requestData.get("refundReason").toString());
            }
            if (requestData.containsKey("refundAmount")) {
                refund.setRefundAmount(new BigDecimal(requestData.get("refundAmount").toString()));
            }
            if (requestData.containsKey("handleNote")) {
                refund.setHandleNote(requestData.get("handleNote").toString());
            }
            if (requestData.containsKey("evidenceImages")) {
                refund.setEvidenceImages(requestData.get("evidenceImages").toString());
            }
            
            // 通过订单号查询订单
             EcOrder queryOrder = new EcOrder();
             queryOrder.setOrderNo(refund.getOrderNo());
             List<EcOrder> orders = ecOrderService.selectEcOrderList(queryOrder);
             if (orders.isEmpty()) {
                 return error("订单不存在");
             }
             EcOrder order = orders.get(0);
             
             // 验证订单是否属于当前用户
             if (userId != null && !order.getUserId().equals(userId)) {
                 return error("无权限操作此订单");
             }
            
            // 验证订单状态是否可以申请退款（只有待发货状态可以申请退款）
            if (!"2".equals(order.getOrderStatus())) {
                return error("当前订单状态不支持申请退款");
            }
            
            // 检查是否已经申请过退款
            EcRefund existingRefund = new EcRefund();
            existingRefund.setOrderNo(order.getOrderNo());
            List<EcRefund> existingRefunds = ecRefundService.selectEcRefundList(existingRefund);
            if (!existingRefunds.isEmpty()) {
                return error("该订单已申请过退款");
            }
            
            // 生成退款单号
            String refundNo = "REF" + System.currentTimeMillis();
            
            // 设置退款信息
            refund.setRefundNo(refundNo);
            refund.setOrderNo(order.getOrderNo());
            refund.setUserId(order.getUserId());
            refund.setOrgId(orgId);
            refund.setRefundAmount(order.getPaymentAmount());
            refund.setRefundStatus("1"); // 1-待审核
            refund.setApplyTime(new Date());
            
            logger.info("[退款申请] 设置退款记录 - 退款单号: {}, 订单号: {}, 用户ID: {}, 组织ID: {}, 退款金额: {}", 
                refundNo, order.getOrderNo(), order.getUserId(), orgId, order.getPaymentAmount());
            
            // 保存退款申请
            int result = ecRefundService.insertEcRefund(refund);
            
            if (result > 0) {
                return success("退款申请提交成功，请等待审核");
            } else {
                return error("退款申请提交失败");
            }
            
        } catch (Exception e) {
            logger.error("申请退款失败", e);
            return error("申请退款失败：" + e.getMessage());
        }
    }
    
    /**
     * 查询订单退款状态
     */
    @GetMapping("/refund/status/{orderNo}")
    public AjaxResult getRefundStatus(@PathVariable("orderNo") String orderNo, @RequestParam(value = "orgId", required = false) Long orgId)
    {
        try {
            EcRefund refund = new EcRefund();
            refund.setOrderNo(orderNo);
            
            // 设置orgId，优先使用请求参数，否则使用当前用户的orgId
            if (orgId != null) {
                refund.setOrgId(orgId);
            } else {
                refund.setOrgId(getOrgId());
            }
            
            List<EcRefund> refunds = ecRefundService.selectEcRefundList(refund);
            
            if (refunds.isEmpty()) {
                return success(null); // 没有退款申请
            }
            
            return success(refunds.get(0)); // 返回最新的退款申请
            
        } catch (Exception e) {
            logger.error("查询退款状态失败", e);
            return error("查询退款状态失败：" + e.getMessage());
        }
    }
    
    /**
     * 提交商品评价
     */
    @Log(title = "提交商品评价", businessType = BusinessType.INSERT)
    @PostMapping("/comment/submit")
    public AjaxResult submitComment(@RequestBody Map<String, Object> commentData)
    {
        try {
            Long userId = SecurityUtils.getUserId();
            if (userId == null) {
                return AjaxResult.error("用户未登录");
            }
            
            // 获取参数
            Long orderId = Long.valueOf(commentData.get("orderId").toString());
            String content = (String) commentData.get("content");
            Integer star = Integer.valueOf(commentData.get("star").toString());
            String images = (String) commentData.get("images"); // 图片路径，逗号分隔
            
            logger.info("提交评价参数 - orderId: {}, content: {}, star: {}, images: {}", 
                orderId, content, star, images);
            
            // 验证订单是否属于当前用户
            EcOrder order = ecOrderService.selectEcOrderByOrderId(orderId);
            if (order == null || !order.getUserId().equals(userId)) {
                return AjaxResult.error("订单不存在或无权限");
            }
            
            // 检查订单状态是否为已完成
            if (!"4".equals(order.getOrderStatus())) {
                return AjaxResult.error("只有已完成的订单才能评价");
            }
            
            // 获取订单中的所有商品
            EcOrderItem queryItem = new EcOrderItem();
            queryItem.setOrderId(orderId);
            List<EcOrderItem> orderItems = ecOrderItemService.selectEcOrderItemList(queryItem);
            
            if (orderItems == null || orderItems.isEmpty()) {
                return AjaxResult.error("订单中没有商品信息");
            }
            
            // 检查是否已经评价过（检查第一个商品即可，因为要么全部评价，要么全部未评价）
            EcProductComment existingComment = new EcProductComment();
            existingComment.setOrderId(orderId);
            existingComment.setUserId(userId);
            List<EcProductComment> existingComments = ecProductCommentService.selectEcProductCommentList(existingComment);
            if (existingComments != null && !existingComments.isEmpty()) {
                return AjaxResult.error("该订单已评价，无法重复评价");
            }
            
            // 获取用户信息
            String userName = SecurityUtils.getUsername();
            
            // 为订单中的每个商品创建评价记录
            int successCount = 0;
            for (EcOrderItem orderItem : orderItems) {
                EcProductComment comment = new EcProductComment();
                comment.setProductId(orderItem.getProductId());
                comment.setOrderId(orderId);
                comment.setUserId(userId);
                comment.setUserName(userName);
                comment.setStar(star);
                comment.setContent(content);
                comment.setImages(images);
                comment.setShowStatus("1"); // 默认显示
                comment.setCreateTime(new Date());
                
                logger.info("为商品{}创建评价记录", orderItem.getProductId());
                
                // 保存评价
                int result = ecProductCommentService.insertEcProductComment(comment);
                if (result > 0) {
                    successCount++;
                    // 更新商品评论数
                    ecProductService.updateProductCommentCount(orderItem.getProductId(), 1);
                }
            }
            
            if (successCount == orderItems.size()) {
                // 评价提交成功后，更新订单的评价时间
                Date currentTime = new Date();
                EcOrder updateOrder = new EcOrder();
                updateOrder.setOrderId(orderId);
                updateOrder.setCommentTime(currentTime);
                
                int updateResult = ecOrderService.updateEcOrder(updateOrder);
                logger.info("更新订单评价时间 - orderId: {}, commentTime: {}, result: {}", 
                    orderId, currentTime, updateResult);
                
                return AjaxResult.success("评价提交成功，共为" + successCount + "个商品添加了评价");
            } else if (successCount > 0) {
                return AjaxResult.success("部分评价提交成功，成功" + successCount + "/" + orderItems.size() + "个商品");
            } else {
                return AjaxResult.error("评价提交失败");
            }
            
        } catch (Exception e) {
            logger.error("提交商品评价失败：" + e.getMessage(), e);
            return AjaxResult.error("评价提交失败：" + e.getMessage());
        }
    }
    
    /**
     * 创建订单
     */
    @PostMapping("/create")
    public AjaxResult createOrder(@RequestBody Map<String, Object> orderData)
    {
        System.out.println("=== 订单创建接口被调用 ===");
        System.out.println("=== 接收到的订单数据: " + orderData);
        
        try {
            // 验证必要的订单参数
            if (orderData.get("userId") == null) {
                return AjaxResult.error("用户ID不能为空");
            }
            if (orderData.get("totalAmount") == null) {
                return AjaxResult.error("订单总金额不能为空");
            }
            // 订单状态默认为待付款（1待付款 2待发货 3待收货 4已完成 5已取消 6已退款）
            String orderStatus = orderData.get("status") != null ? 
                orderData.get("status").toString() : "1";
            if (orderData.get("items") == null) {
                return AjaxResult.error("订单商品信息不能为空");
            }
            
            Long userId = Long.valueOf(orderData.get("userId").toString());
            if (userId == null) {
                return AjaxResult.error("用户ID不能为空");
            }
            
            // 获取组织ID，如果前端没有传递则使用默认值
            Long orgId = orderData.get("orgId") != null ? 
                Long.valueOf(orderData.get("orgId").toString()) : getOrgId();
            System.out.println("=== 使用的组织ID: " + orgId);
            
            // 获取用户默认地址
            EcUserAddress defaultAddress = ecUserAddressService.selectDefaultAddressByUserId(userId);
            
            // 创建订单对象
            EcOrder order = new EcOrder();
            order.setUserId(userId);
            order.setOrgId(orgId);
            order.setOrderNo(generateOrderNo());
            BigDecimal totalAmount = new BigDecimal(orderData.get("totalAmount").toString());
            order.setTotalAmount(totalAmount);
            // 设置实付金额，初始时等于订单总金额
            order.setPaymentAmount(totalAmount);
            order.setOrderStatus(orderStatus);
            order.setCreateTime(new Date());
            System.out.println("=== 创建订单时设置金额 ===");
            System.out.println("订单总金额: " + totalAmount);
            System.out.println("实付金额: " + totalAmount);
            
            // 设置收货地址信息
            if (defaultAddress != null) {
                order.setReceiverName(defaultAddress.getReceiverName());
                order.setReceiverPhone(defaultAddress.getReceiverPhone());
                order.setReceiverProvince(defaultAddress.getProvince());
                order.setReceiverCity(defaultAddress.getCity());
                order.setReceiverDistrict(defaultAddress.getDistrict());
                order.setReceiverAddress(defaultAddress.getDetailAddress());
                order.setReceiverZip(defaultAddress.getZipCode());
            }
            
            // 处理订单商品前先检查库存
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> orderItems = (List<Map<String, Object>>) orderData.get("items");
            if (orderItems != null && !orderItems.isEmpty()) {
                // 批量检查库存
                for (Map<String, Object> itemData : orderItems) {
                    if (itemData.get("skuId") != null && itemData.get("quantity") != null) {
                        Long skuId = Long.valueOf(itemData.get("skuId").toString());
                        Long quantity = Long.valueOf(itemData.get("quantity").toString());
                        
                        // 检查库存是否充足
                        if (!ecStockService.checkStock(skuId, quantity)) {
                            // 获取SKU信息用于错误提示
                            EcProductSku sku = ecProductSkuService.selectEcProductSkuBySkuId(skuId);
                            String skuName = sku != null ? sku.getSkuName() : "商品";
                            Long currentStock = ecStockService.getCurrentStock(skuId);
                            
                            logger.warn("库存不足，无法创建订单: skuId={}, 需要数量={}, 当前库存={}", 
                                       skuId, quantity, currentStock);
                            return AjaxResult.error(String.format("%s库存不足，当前库存：%d，需要数量：%d", 
                                                                 skuName, currentStock, quantity));
                        }
                    }
                }
            }
            
            // 保存订单
            int result = ecOrderService.insertEcOrder(order);
            if (result > 0) {
                // 处理订单商品
                if (orderItems != null && !orderItems.isEmpty()) {
                    for (Map<String, Object> itemData : orderItems) {
                        // 检查必要的参数是否存在
                        if (itemData.get("productId") == null || itemData.get("quantity") == null || 
                            itemData.get("productPrice") == null || itemData.get("subtotal") == null) {
                            logger.error("订单商品数据不完整: {}", itemData);
                            return AjaxResult.error("订单商品数据不完整");
                        }
                        
                        EcOrderItem orderItem = new EcOrderItem();
                        orderItem.setOrderId(order.getOrderId());
                        orderItem.setOrderNo(order.getOrderNo());
                        orderItem.setOrgId(orgId);
                        
                        Long productId = Long.valueOf(itemData.get("productId").toString());
                        orderItem.setProductId(productId);
                        
                        // 根据商品ID查询商品信息，获取商品名称、品牌、分类等信息
                        EcProduct product = ecProductService.selectEcProductByProductId(productId);
                        if (product != null) {
                            orderItem.setProductName(product.getProductName());
                            orderItem.setRealProductName(product.getProductName());
                            orderItem.setProductImage(product.getMainImage());
                            
                            // 获取品牌信息
                            if (product.getBrandId() != null) {
                                EcBrand brand = ecBrandService.selectEcBrandByBrandId(product.getBrandId());
                                if (brand != null) {
                                    orderItem.setProductBrand(brand.getBrandName());
                                    orderItem.setBrandName(brand.getBrandName());
                                }
                            }
                            
                            // 获取分类信息
                            if (product.getCategoryId() != null) {
                                EcCategory category = ecCategoryService.selectEcCategoryByCategoryId(product.getCategoryId());
                                if (category != null) {
                                    orderItem.setProductCategory(category.getCategoryName());
                                    orderItem.setCategoryName(category.getCategoryName());
                                }
                            }
                        } else {
                            // 如果商品不存在，设置默认值避免数据库错误
                            logger.warn("商品ID {} 不存在，使用默认商品名称", productId);
                            orderItem.setProductName("未知商品");
                            orderItem.setRealProductName("未知商品");
                        }
                        
                        Long skuId = itemData.get("skuId") != null ? Long.valueOf(itemData.get("skuId").toString()) : null;
                        orderItem.setSkuId(skuId);
                        
                        // 获取SKU规格信息（直接查询，不使用组织ID过滤）
                         if (skuId != null) {
                             EcProductSku sku = ecProductSkuService.selectEcProductSkuBySkuId(skuId);
                             if (sku != null) {
                                 System.out.println("=== 创建订单时SKU信息获取成功 ===");
                                 System.out.println("SKU ID: " + sku.getSkuId());
                                 System.out.println("SKU名称: " + sku.getSkuName());
                                 System.out.println("SKU规格信息: " + sku.getSpecInfo());
                                 orderItem.setProductSpec(sku.getSpecInfo());
                                 orderItem.setSkuName(sku.getSkuName());
                                 // 如果SKU有图片，优先使用SKU图片
                                 if (sku.getImage() != null && !sku.getImage().isEmpty()) {
                                     orderItem.setProductImage(sku.getImage());
                                 }
                             } else {
                                 System.out.println("=== 创建订单时SKU信息获取失败 ===");
                                 System.out.println("SKU ID: " + skuId);
                             }
                         }
                        
                        orderItem.setProductQuantity(Long.valueOf(itemData.get("quantity").toString()));
                        orderItem.setProductPrice(new BigDecimal(itemData.get("productPrice").toString()));
                        orderItem.setProductTotalPrice(new BigDecimal(itemData.get("subtotal").toString()));
                        
                        ecOrderItemService.insertEcOrderItem(orderItem);
                    }
                }
                
                Map<String, Object> responseData = new HashMap<>();
                responseData.put("orderId", order.getOrderId());
                responseData.put("orderNo", order.getOrderNo());
                
                return AjaxResult.success("订单创建成功", responseData);
            } else {
                return AjaxResult.error("订单创建失败");
            }
            
        } catch (Exception e) {
            logger.error("创建订单失败：" + e.getMessage(), e);
            return AjaxResult.error("创建订单失败：" + e.getMessage());
        }
    }
    
    /**
     * 生成订单号
     * 格式：ORD + 时间戳后8位 + 4位随机数
     */
    private String generateOrderNo() {
        // 获取当前时间戳
        long timestamp = System.currentTimeMillis();
        String timestampStr = String.valueOf(timestamp);
        // 取时间戳后8位
        String last8Digits = timestampStr.substring(timestampStr.length() - 8);
        
        // 生成4位随机数
        Random random = new Random();
        int randomNum = random.nextInt(9000) + 1000; // 生成1000-9999的随机数
        
        return "ORD" + last8Digits + randomNum;
    }
    
    /**
     * 检查订单商品是否已评价
     */
    @GetMapping("/comment/check/{orderId}/{productId}")
    public AjaxResult checkCommentStatus(@PathVariable("orderId") Long orderId, @PathVariable("productId") Long productId)
    {
        try {
            Long userId = SecurityUtils.getUserId();
            Long orgId = getOrgId();
            if (userId == null) {
                return AjaxResult.error("用户未登录");
            }
            
            // 验证订单是否属于当前用户
            EcOrder order = ecOrderService.selectEcOrderByOrderId(orderId);
            if (order == null || !order.getUserId().equals(userId)) {
                return AjaxResult.error("订单不存在或无权限");
            }
            
            // 检查是否已经评价过
            EcProductComment existingComment = new EcProductComment();
            existingComment.setOrderId(orderId);
            existingComment.setProductId(productId);
            existingComment.setUserId(userId);
            List<EcProductComment> existingComments = ecProductCommentService.selectEcProductCommentList(existingComment);
            
            Map<String, Object> result = new HashMap<>();
            result.put("hasCommented", existingComments != null && !existingComments.isEmpty());
            if (existingComments != null && !existingComments.isEmpty()) {
                result.put("comment", existingComments.get(0));
            }
            
            return AjaxResult.success(result);
            
        } catch (Exception e) {
            logger.error("检查评价状态失败：" + e.getMessage(), e);
            return AjaxResult.error("检查评价状态失败：" + e.getMessage());
        }
    }
    
    /**
     * 上传评价图片
     */
    @PostMapping("/comment/upload")
    public AjaxResult uploadCommentImage(@RequestParam("file") MultipartFile file)
    {
        try {
            if (file.isEmpty()) {
                return AjaxResult.error("上传文件不能为空");
            }
            
            // 上传文件到腾讯云COS
            String fileUrl = tencentCosService.uploadFile(file);
            
            Map<String, Object> result = new HashMap<>();
            result.put("fileName", fileUrl.substring(fileUrl.lastIndexOf("/") + 1));
            result.put("url", fileUrl);
            
            return AjaxResult.success(result);
            
        } catch (Exception e) {
            logger.error("上传评价图片失败：" + e.getMessage(), e);
            return AjaxResult.error("上传失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新订单收货地址
     */
    @Log(title = "更新订单地址", businessType = BusinessType.UPDATE)
    @PostMapping("/updateAddress")
    public AjaxResult updateOrderAddress(@RequestBody Map<String, Object> requestData)
    {
        try {
            // 从请求体中获取用户ID，支持匿名访问
            Long userId = requestData.get("userId") != null ? Long.valueOf(requestData.get("userId").toString()) : null;
            Long orgId = getOrgId();
            if (userId == null) {
                return AjaxResult.error("用户ID不能为空");
            }
            
            Long orderId = Long.valueOf(requestData.get("orderId").toString());
            Long addressId = Long.valueOf(requestData.get("addressId").toString());
            
            // 验证订单是否属于当前用户（直接通过orderId查询，不使用orgId过滤）
            EcOrder order = ecOrderService.selectEcOrderByOrderId(orderId);
            if (order == null) {
                return AjaxResult.error("订单不存在");
            }
            
            // 验证订单是否属于当前用户
            if (!order.getUserId().equals(userId)) {
                return AjaxResult.error("无权限操作此订单");
            }
            
            // 只有待付款状态的订单才能修改地址
            if (!"1".equals(order.getOrderStatus())) {
                return AjaxResult.error("只有待付款订单才能修改收货地址");
            }
            
            // 获取新的收货地址信息（直接在查询中验证用户权限）
            EcUserAddress newAddress = ecUserAddressService.selectEcUserAddressByAddressIdAndUserId(addressId, userId);
            if (newAddress == null) {
                return AjaxResult.error("收货地址不存在或无权限");
            }
            
            // 更新订单的收货地址信息
            order.setReceiverName(newAddress.getReceiverName());
            order.setReceiverPhone(newAddress.getReceiverPhone());
            order.setReceiverProvince(newAddress.getProvince());
            order.setReceiverCity(newAddress.getCity());
            order.setReceiverDistrict(newAddress.getDistrict());
            order.setReceiverAddress(newAddress.getDetailAddress());
            order.setReceiverZip(newAddress.getZipCode());
            
            int result = ecOrderService.updateEcOrder(order);
            if (result > 0) {
                return AjaxResult.success("地址更新成功");
            } else {
                return AjaxResult.error("地址更新失败");
            }
            
        } catch (Exception e) {
            logger.error("更新订单地址失败：" + e.getMessage(), e);
            return AjaxResult.error("更新订单地址失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取当前用户的订单统计信息
     */
    @GetMapping("/stats")
    public AjaxResult getOrderStats(@RequestParam(value = "userId", required = false) Long userId, @RequestParam(value = "orgId", required = false) Long orgId)
    {
        System.out.println("[DEBUG] ========== 开始获取订单统计 ==========");
        System.out.println("[DEBUG] 请求入参: userId=" + userId + ", orgId=" + orgId);
        System.out.println("[DEBUG] 请求时间: " + new java.util.Date());
        
        try {
            // 优先从SecurityUtils获取用户ID，如果获取失败则从请求参数获取
            Long currentUserId = null;
            try {
                System.out.println("[DEBUG] 尝试从SecurityUtils获取用户ID");
                currentUserId = SecurityUtils.getUserId();
                System.out.println("[DEBUG] SecurityUtils获取用户ID成功: " + currentUserId);
            } catch (Exception e) {
                System.out.println("[DEBUG] SecurityUtils获取用户ID异常详情: " + e.getClass().getSimpleName() + " - " + e.getMessage());
                e.printStackTrace();
                if (userId != null) {
                    currentUserId = userId;
                    System.out.println("[DEBUG] 使用请求参数中的用户ID: " + currentUserId);
                }
            }
            
            // 如果没有传入orgId，使用默认值103
            if (orgId == null) {
                orgId = 103L;
            }
            System.out.println("[DEBUG] 最终使用的参数 - userId: " + currentUserId + ", orgId: " + orgId);
            
            if (currentUserId == null) {
                System.out.println("[DEBUG] 用户ID为空，返回错误");
                return error("用户ID不能为空");
            }
            
            // 创建查询条件
            EcOrder queryOrder = new EcOrder();
            queryOrder.setUserId(currentUserId);
            queryOrder.setOrgId(orgId);
            

            
            // 统计各状态订单数量
            Map<String, Long> stats = new HashMap<>();
            
            // 待付款订单 (status = 1)
            System.out.println("[DEBUG] 查询待付款订单，查询条件: userId=" + currentUserId + ", orgId=" + orgId + ", status=1");
            queryOrder.setOrderStatus("1");
            List<EcOrder> pendingOrders = ecOrderService.selectEcOrderList(queryOrder);
            System.out.println("[DEBUG] 待付款订单查询结果: " + (pendingOrders != null ? pendingOrders.size() : "null") + "条");
            stats.put("pending", (long) pendingOrders.size());
            
            // 待发货订单 (status = 2)
            System.out.println("[DEBUG] 查询待发货订单，查询条件: userId=" + currentUserId + ", orgId=" + orgId + ", status=2");
            queryOrder.setOrderStatus("2");
            List<EcOrder> toShipOrders = ecOrderService.selectEcOrderList(queryOrder);
            System.out.println("[DEBUG] 待发货订单查询结果: " + (toShipOrders != null ? toShipOrders.size() : "null") + "条");
            stats.put("shipped", (long) toShipOrders.size());
            
            // 待收货订单 (status = 3)
            System.out.println("[DEBUG] 查询待收货订单，查询条件: userId=" + currentUserId + ", orgId=" + orgId + ", status=3");
            queryOrder.setOrderStatus("3");
            List<EcOrder> toReceiveOrders = ecOrderService.selectEcOrderList(queryOrder);
            System.out.println("[DEBUG] 待收货订单查询结果: " + (toReceiveOrders != null ? toReceiveOrders.size() : "null") + "条");
            stats.put("delivered", (long) toReceiveOrders.size());
            
            System.out.println("[DEBUG] 订单统计结果: " + stats);
            System.out.println("[DEBUG] 准备返回成功响应");
            AjaxResult result = success(stats);
            System.out.println("[DEBUG] 返回响应数据: " + result);
            System.out.println("[DEBUG] ========== 订单统计完成 ==========");
            return result;
        } catch (Exception e) {
            System.out.println("[ERROR] 获取订单统计异常: " + e.getClass().getSimpleName() + " - " + e.getMessage());
            e.printStackTrace();
            AjaxResult errorResult = error("获取订单统计失败：" + e.getMessage());
            System.out.println("[ERROR] 返回错误响应: " + errorResult);
            System.out.println("[DEBUG] ========== 订单统计异常结束 ==========");
            return errorResult;
        }
    }
    
    /**
     * 使用优惠券更新订单实付金额
     */
    @Log(title = "使用优惠券更新订单金额", businessType = BusinessType.UPDATE)
    @PostMapping("/applyCoupon")
    public AjaxResult applyCouponToOrder(@RequestBody Map<String, Object> requestData) {
        try {
            Long orderId = Long.valueOf(requestData.get("orderId").toString());
            Long userId = requestData.get("userId") != null ? Long.valueOf(requestData.get("userId").toString()) : null;
            Long orgId = requestData.get("orgId") != null ? Long.valueOf(requestData.get("orgId").toString()) : getOrgId();
            BigDecimal discountAmount = new BigDecimal(requestData.get("discountAmount").toString());
            
            System.out.println("=== 使用优惠券更新订单金额 ===");
            System.out.println("订单ID: " + orderId);
            System.out.println("用户ID: " + userId);
            System.out.println("组织ID: " + orgId);
            System.out.println("优惠金额: " + discountAmount);
            
            // 查询订单
            EcOrder order = ecOrderService.selectEcOrderByOrderId(orderId);
            if (order == null) {
                return AjaxResult.error("订单不存在");
            }
            
            // 验证用户权限（如果提供了userId）
            if (userId != null && !order.getUserId().equals(userId)) {
                return AjaxResult.error("无权限访问此订单");
            }
            
            // 验证组织权限
            if (!order.getOrgId().equals(orgId)) {
                return AjaxResult.error("订单不属于当前组织");
            }
            
            // 计算实付金额 = 订单总金额 - 优惠金额
            BigDecimal paymentAmount = order.getTotalAmount().subtract(discountAmount);
            
            // 确保实付金额不小于0.01元
            BigDecimal minAmount = new BigDecimal("0.01");
            if (paymentAmount.compareTo(minAmount) < 0) {
                paymentAmount = minAmount;
            }
            
            // 更新订单的实付金额和优惠券金额
            order.setPaymentAmount(paymentAmount);
            order.setCouponAmount(discountAmount);
            
            System.out.println("订单总金额: " + order.getTotalAmount());
            System.out.println("优惠券金额: " + discountAmount);
            System.out.println("实付金额: " + paymentAmount);
            
            int result = ecOrderService.updateEcOrder(order);
            
            if (result > 0) {
                return AjaxResult.success("优惠券应用成功", order);
            } else {
                return AjaxResult.error("优惠券应用失败");
            }
        } catch (Exception e) {
            System.err.println("使用优惠券更新订单金额异常: " + e.getMessage());
            e.printStackTrace();
            return AjaxResult.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 根据订单号查询物流信息
     */
    @GetMapping("/logistics/{orderNo}")
    public AjaxResult getLogisticsByOrderNo(@PathVariable("orderNo") String orderNo, @RequestParam(value = "userId", required = false) Long userId)
    {
        try {
            System.out.println("查询物流信息 - 订单号: " + orderNo + ", 用户ID: " + userId);
            
            // 首先验证订单是否存在且用户有权限访问（不使用org_id过滤）
            EcOrder queryOrder = new EcOrder();
            queryOrder.setOrderNo(orderNo);
            System.out.println("查询订单条件 - 订单号: " + orderNo);
            List<EcOrder> orderList = ecOrderService.selectEcOrderList(queryOrder);
            System.out.println("查询到的订单数量: " + (orderList != null ? orderList.size() : 0));
            
            if (orderList == null || orderList.isEmpty()) {
                System.out.println("订单不存在");
                return AjaxResult.error("订单不存在");
            }
            
            EcOrder order = orderList.get(0);
            System.out.println("找到订单 - ID: " + order.getOrderId() + ", 用户ID: " + order.getUserId() + ", 状态: " + order.getOrderStatus());
            
            // 验证用户权限（如果提供了userId）
            if (userId != null && !order.getUserId().equals(userId)) {
                System.out.println("用户权限验证失败 - 订单用户ID: " + order.getUserId() + ", 请求用户ID: " + userId);
                return AjaxResult.error("无权限访问此订单");
            }
            
            // 查询物流信息（只根据订单号查询）
            System.out.println("开始查询物流信息 - 订单号: " + orderNo);
            EcLogistics logistics = ecLogisticsService.selectEcLogisticsByOrderNo(orderNo);
            System.out.println("物流查询结果: " + (logistics != null ? "找到物流信息" : "未找到物流信息"));
            
            if (logistics == null) {
                return AjaxResult.error("暂无物流信息");
            }
            System.out.println("找到物流信息 - 物流公司: " + logistics.getLogisticsCompanyName() + ", 运单号: " + logistics.getLogisticsNo());
            
            return AjaxResult.success(logistics);
            
        } catch (Exception e) {
            System.err.println("查询物流信息异常: " + e.getMessage());
            e.printStackTrace();
            return AjaxResult.error("查询物流信息失败: " + e.getMessage());
        }
    }

}